<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div class="filter-header">
        <i class="el-icon-filter"></i>
        <span>数据筛选</span>
      </div>
      <el-select 
        v-model="queryParams.semester" 
        placeholder="请选择开课学期"
        class="semester-select"
        @change="fetchData"
      >
        <el-option 
          v-for="(semester,index) in availableSemesters" 
          :key="index" 
          :value="semester"
          :label="semester"
        />
      </el-select>
    </el-card>

    <el-card class="abnormal-container" shadow="never" v-if="abnormalStudents.length">
      <div class="section-header">
        <i class="el-icon-warning-outline"></i>
        <h3>异常学生列表（评分波动性过小）</h3>
      </div>
      <div class="abnormal-list">
        <el-tag 
          v-for="student in abnormalStudents" 
          :key="student.id"
          type="danger"
          class="abnormal-tag"
        >
          {{ student.id }} (Z-score均值: {{ student.avgZScore.toFixed(2) }})
        </el-tag>
      </div>
    </el-card>

    <el-card class="chart-container" shadow="never">
      <div class="section-header">
        <i class="el-icon-data-analysis"></i>
        <h3>评教成绩分布分析</h3>
      </div>
      <div ref="chart" style="width: 100%; height: 500px"></div>
    </el-card>

    <el-pagination
      class="pagination-container"
      background 
      layout="prev, pager, next"
      :total="total"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      @current-change="fetchData"
    />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getEvaluate } from '@/api/table'
import { getSemester1 } from '@/api/dashboard'

export default {
  data() {
    return {
      availableSemesters: [],
      chart: null,
      rawData: [],
      abnormalStudents: [],
      teacherScores: {},
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 600,
        semester: '',
      },
      zScoreThreshold: 0.7 // Z-score阈值，可调整
    }
  },
  created(){
    getSemester1().then(res=>{
      this.availableSemesters=res.data
    })
  },

  methods: {
    async fetchData() {
      try {
        const res = await getEvaluate(this.queryParams)
        if (res?.data) {
          this.total = res.data.total
          this.rawData = res.data.rows
          this.processData()
          this.initChart()
          window.addEventListener('resize', this.handleResize)
        }
      } catch (error) {
        console.error('数据加载失败:', error)
        this.$message.error('数据加载失败')
      }
    },

    processData() {
      const groups = {}
      const teacherGroups = {}
      this.abnormalStudents = []

      // 数据分组
      this.rawData.forEach(item => {
        const groupKey = `${item.studentId}-${item.subId}-${item.teacherId}`
        groups[groupKey] = groups[groupKey] || []
        groups[groupKey].push(item)

        const teacherKey = `${item.teacherId}-${item.subId}`
        teacherGroups[teacherKey] = teacherGroups[teacherKey] || []
        teacherGroups[teacherKey].push(item)
      })

      // Z-score异常检测
      Object.entries(groups).forEach(([key, items]) => {
        if (items.length < 6) return
        
        const scores = items.map(i => i.evaScore)
        const mean = scores.reduce((a, b) => a + b, 0) / scores.length
        const stdDev = Math.sqrt(scores.reduce((a, b) => a + (b - mean)**2, 0) / scores.length)
        
        // 处理标准差为0的情况
        if (stdDev === 0) {
          this.abnormalStudents.push({
            id: items[0].studentId,
            avgZScore: 0
          })
          return
        }

        const zScores = scores.map(s => (s - mean) / stdDev)
        const avgZScore = zScores.reduce((a, b) => a + Math.abs(b), 0) / zScores.length

        // 如果平均Z-score绝对值小于阈值
        if (avgZScore < this.zScoreThreshold) {
          this.abnormalStudents.push({
            id: items[0].studentId,
            avgZScore
          })
        }
      })

      // 处理教师评分数据
      this.teacherScores = {} // 清空旧数据
      Object.entries(teacherGroups).forEach(([key, items]) => {
        const studentScores = {}
        
        // 按学生汇总总分
        items.forEach(item => {
          const stuKey = `${item.studentId}-${item.subId}`
          studentScores[stuKey] = (studentScores[stuKey] || 0) + item.evaScore
        })
        
        // 存储所有学生总分数组
        this.teacherScores[key] = Object.values(studentScores)
      })
    },

    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      
      const option = {
        title: {
          text: '评教成绩分布分析',
          left: 'center',
          textStyle: {
            color: '#666',
            fontSize: 18
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0].data
            return `最小值: ${data[1]}<br/>
                     Q1: ${data[2]}<br/>
                     Q2: ${data[3]}<br/>
                     Q3: ${data[4]}<br/>
                     最大值: ${data[5]}`
          }
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            rotate: 45,
            color: '#666'
          },
          data:Object.keys(this.teacherScores)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#666'
          }
        },
        series: [{
          type: 'boxplot',
          itemStyle: {
            color: '#409EFF',
            borderColor: '#304156'
          },
          data: Object.values(this.teacherScores).map(scores => {      
            const sorted = [...scores].sort((a, b) => a - b)
            return [
              Math.min(...sorted),
              sorted[Math.floor(sorted.length * 0.25)],
              sorted[Math.floor(sorted.length * 0.5)],
              sorted[Math.floor(sorted.length * 0.75)],
              Math.max(...sorted)
            ]
          })
        }],
        grid: {
          containLabel: true,
          left: '3%',
          right: '3%',
          bottom: '15%'
        }
      }
      this.chart.setOption(option)
    },

    handleResize() {
      this.chart?.resize()
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chart?.dispose()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-header {
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.filter-header i {
  margin-right: 8px;
}

.semester-select {
  width: 300px;
}

.abnormal-container {
  margin: 20px 0;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #606266;
}

.section-header i {
  margin-right: 8px;
  font-size: 18px;
}

.abnormal-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.abnormal-tag {
  margin: 5px;
  font-size: 14px;
}

.chart-container {
  margin: 20px 0;
  padding: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
</style>

